package com.youzi.mdtool.controller;

import com.youzi.mdtool.conf.MDConfig;
import com.youzi.mdtool.entity.Catalog;
import com.youzi.mdtool.util.FileUtil;
import com.youzi.mdtool.util.R;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Andrew.Song
 * @Date : 2018-8-27 18:02
 */
@RestController
public class MainController {

    private static final Logger log = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private FileUtil fileService;
    @Autowired
    private MDConfig config;


    @GetMapping(value = "queryCatelogTree")
    public R queryCatalog(){
        R r = new R(R.SUCCESS);
        List<Catalog> catalogs = new ArrayList<>();
        int path_max = config.getMaxCount();
        Catalog catalog;
        for (int i = 0; i < config.getPath().size(); i++) {
            if(i > path_max){
                break;
            }
            catalog = fileService.iteratorFile(config.getPath().get(i));
            catalogs.add(catalog);
        }
        r.setObject(catalogs);
        return r;

    }

    @RequestMapping(value = "queryContent")
    public R queryContent(String path){
        R r = new R(R.SUCCESS);
        if(StringUtils.isEmpty(path)){
            r.setCode(R.ERROR);
            r.setMsg("参数错误");
            return r;
        }
        File file = new File(path);
        if(!file.getName().toLowerCase().endsWith("md")){
            r.setCode(R.ERROR);
            r.setMsg("不支持的文件格式");
            return r;
        }
        try {
            String string = FileUtils.readFileToString(file, "UTF-8");
            r.setObject(string);
            return r;
        } catch (IOException e) {
            log.error("读取markdown内容,系统异常:",e);
            r.setCode(R.ERROR);
            r.setMsg("系统异常");
            return r;
        }
    }
}
